<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>详解Java对象的引用及赋值 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-04-23 18:21">
      April 23, 2019 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      35
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="细节-详解Java中对象的引用及赋值"><a href="#细节-详解Java中对象的引用及赋值" class="headerlink" title="细节 : 详解Java中对象的引用及赋值"></a>细节 : 详解<code>Java</code>中对象的引用及赋值</h2><h3 id="问题引入"><a href="#问题引入" class="headerlink" title="问题引入"></a>问题引入</h3><ol>
<li><em>前言</em></li>
</ol>
<p><em>前些天学习数据结构与算法时特意写了一篇名为<code>详解Linked-list的实现方式及其应用</code>的文章,其中<code>循环链表</code>的代码中就淋漓尽致地体现了Java中<code>对象</code>的引用与赋值</em></p>
<ol start="2">
<li><p><em>循环链表的实现</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.linkedlist;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: CircularLinkedList
 * <span class="hljs-doctag">@Description</span>: 操作循环链表
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@param</span> &lt;T&gt;
 * <span class="hljs-doctag">@date</span>: Apr 16, 2019 7:25:36 PM
 * 
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CircularLinkedList</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;

	<span class="hljs-comment">// get the length of the circular linked list</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getLength</span><span class="hljs-params">(ListNode&lt;T&gt; headNode)</span> </span>&#123;
		<span class="hljs-keyword">int</span> length = <span class="hljs-number">0</span>;
		ListNode&lt;T&gt; currentNode = headNode;
		<span class="hljs-keyword">while</span> (currentNode != <span class="hljs-keyword">null</span>) &#123;
			currentNode = currentNode.getNext();
			length++;
			<span class="hljs-keyword">if</span> (currentNode == headNode) &#123;
				<span class="hljs-keyword">break</span>;
			&#125;
		&#125;
		<span class="hljs-keyword">return</span> length;
	&#125;

	<span class="hljs-comment">// traverse the node of the circular linked list</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">traverseNode</span><span class="hljs-params">(ListNode&lt;T&gt; headNode)</span> </span>&#123;
		System.out.println(<span class="hljs-string">"\n### [headNode]-address : "</span> + headNode + <span class="hljs-string">"\n"</span>);
		ListNode&lt;T&gt; currentNode = headNode;
		<span class="hljs-keyword">while</span> (currentNode != <span class="hljs-keyword">null</span>) &#123;
			System.out.print(currentNode.getData() + <span class="hljs-string">" -&gt; "</span>);
			currentNode = currentNode.getNext();
			<span class="hljs-keyword">if</span> (currentNode == headNode) &#123;
				<span class="hljs-keyword">break</span>;
			&#125;
		&#125;
		System.out.print(<span class="hljs-string">"headNode("</span> + currentNode.getData() + <span class="hljs-string">")\n"</span>);
	&#125;

	<span class="hljs-comment">// add new node at the tail of linked list</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertAtListTail</span><span class="hljs-params">(ListNode&lt;T&gt; headNode, ListNode&lt;T&gt; newNode)</span> </span>&#123;

		ListNode&lt;T&gt; currentNode = headNode;
		<span class="hljs-keyword">while</span> (currentNode.getNext() != headNode) &#123;
			<span class="hljs-comment">//// 注意: 由于`currentNode`无变化,导致`currentNode.getNext() != headNode`继而进入进入死循环 !////</span>
			<span class="hljs-comment">// currentNode.setNext(currentNode.getNext());</span>
			currentNode = currentNode.getNext();
		&#125;
		newNode.setNext(newNode);
		<span class="hljs-keyword">if</span> (headNode == <span class="hljs-keyword">null</span>) &#123;
			headNode = newNode;
		&#125; <span class="hljs-keyword">else</span> &#123;
			newNode.setNext(headNode);
			currentNode.setNext(newNode);
		&#125;
	&#125;

	<span class="hljs-comment">// add new node at the header of linked list</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> ListNode&lt;T&gt; <span class="hljs-title">insertAtListHeader</span><span class="hljs-params">(ListNode&lt;T&gt; headNode, ListNode&lt;T&gt; newNode)</span> </span>&#123;

		ListNode&lt;T&gt; currentNode = headNode;
		<span class="hljs-keyword">while</span> (currentNode.getNext() != headNode) &#123;
			currentNode = currentNode.getNext();<span class="hljs-comment">// 尾节点</span>
		&#125;
		newNode.setNext(newNode);<span class="hljs-comment">// 指针指向自身</span>
		<span class="hljs-keyword">if</span> (headNode == <span class="hljs-keyword">null</span>) &#123;
			headNode = newNode;
		&#125;
		newNode.setNext(headNode);
		currentNode.setNext(newNode);
		<span class="hljs-comment">// 注意: 此时链表头结点已更新! 所以应该返回更新后的头节点继而避免遍历时出现死循环!!!</span>
		headNode = newNode;
		<span class="hljs-keyword">return</span> headNode;
	&#125;

	<span class="hljs-comment">// add the new node by the specified index</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> ListNode&lt;T&gt; <span class="hljs-title">insertNodeByIndex</span><span class="hljs-params">(ListNode&lt;T&gt; headNode, ListNode&lt;T&gt; newNode, <span class="hljs-keyword">int</span> position)</span> </span>&#123;

		<span class="hljs-keyword">if</span> (headNode == <span class="hljs-keyword">null</span>) &#123;
			System.out.println(<span class="hljs-string">"Error: the circular list is empty !"</span>);
			<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (position == <span class="hljs-number">1</span>) &#123;
			insertAtListHeader(headNode, newNode);
		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (position == getLength(headNode)) &#123;
			insertAtListTail(headNode, newNode);
		&#125; <span class="hljs-keyword">else</span> &#123;
			ListNode&lt;T&gt; currentNode = headNode;
			ListNode&lt;T&gt; temp = headNode;
			<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; position - <span class="hljs-number">1</span>; i++) &#123;
				temp = currentNode;<span class="hljs-comment">// 待插节点的前节点</span>
				currentNode = currentNode.getNext();<span class="hljs-comment">// 待插节点</span>
			&#125;
			temp.setNext(newNode);
			newNode.setNext(currentNode);
		&#125;
		<span class="hljs-keyword">return</span> headNode;
	&#125;

	<span class="hljs-comment">// delete the last node</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteLastNode</span><span class="hljs-params">(ListNode&lt;T&gt; headNode)</span> </span>&#123;

		ListNode&lt;T&gt; temp = headNode;
		ListNode&lt;T&gt; currentNode = headNode;
		<span class="hljs-keyword">if</span> (headNode == <span class="hljs-keyword">null</span>) &#123;
			System.err.println(<span class="hljs-string">"Error: the circular list is empty !"</span>);
		&#125;
		<span class="hljs-keyword">while</span> (currentNode.getNext() != headNode) &#123;
			temp = currentNode; <span class="hljs-comment">// 尾节点的前一个节点</span>
			currentNode = currentNode.getNext();
		&#125;
		temp.setNext(headNode);
		currentNode = <span class="hljs-keyword">null</span>;
	&#125;

	<span class="hljs-comment">// delete the header node</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> ListNode&lt;T&gt; <span class="hljs-title">deleteHeaderNode</span><span class="hljs-params">(ListNode&lt;T&gt; headNode)</span> </span>&#123;
		ListNode&lt;T&gt; currentNode = headNode;
		<span class="hljs-keyword">if</span> (headNode == <span class="hljs-keyword">null</span>) &#123;
			System.err.println(<span class="hljs-string">"Error: the circular list is empty !"</span>);
			<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
		&#125;

		<span class="hljs-keyword">while</span> (currentNode.getNext() != headNode) &#123;
			<span class="hljs-comment">// currentNode.setNext(currentNode.getNext());//死循环</span>
			currentNode = currentNode.getNext();
		&#125;
		currentNode.setNext(headNode.getNext());
		<span class="hljs-comment">// 注意: 此时链表头结点已更新! 所以应该返回更新后的头节点继而避免遍历时出现死循环!!!</span>
		headNode = headNode.getNext();
		<span class="hljs-keyword">return</span> headNode;
	&#125;

	<span class="hljs-comment">// delete the node by the specified index</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> ListNode&lt;T&gt; <span class="hljs-title">deleteNodeByIndex</span><span class="hljs-params">(ListNode&lt;T&gt; headNode, <span class="hljs-keyword">int</span> position)</span> </span>&#123;

		<span class="hljs-keyword">if</span> (headNode == <span class="hljs-keyword">null</span>) &#123;
			System.out.println(<span class="hljs-string">"Error: the circular linked list is empty !"</span>);
			<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (position == <span class="hljs-number">1</span>) &#123;
			deleteHeaderNode(headNode);
		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (position == getLength(headNode)) &#123;
			deleteLastNode(headNode);
		&#125; <span class="hljs-keyword">else</span> &#123;
			ListNode&lt;T&gt; currentNode = headNode;
			ListNode&lt;T&gt; temp = headNode;
			<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; position - <span class="hljs-number">1</span>; i++) &#123;
				temp = currentNode;<span class="hljs-comment">// 待删节点的前节点</span>
				currentNode = currentNode.getNext();<span class="hljs-comment">// 待删节点</span>
			&#125;
			temp.setNext(currentNode.getNext());
		&#125;

		<span class="hljs-keyword">return</span> headNode;
	&#125;

	<span class="hljs-comment">// Test</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;

		<span class="hljs-comment">// 初始化链表头结点</span>
		CircularLinkedList&lt;Integer&gt; list = <span class="hljs-keyword">new</span> CircularLinkedList&lt;&gt;();
		ListNode&lt;Integer&gt; headNode = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		headNode.setData(<span class="hljs-number">1</span>);<span class="hljs-comment">// 初始化链表头结点</span>
		headNode.setNext(headNode);<span class="hljs-comment">// 节点指针指向自身</span>

		<span class="hljs-comment">// 初始化待插入的链表节点</span>
		ListNode&lt;Integer&gt; a = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		a.setData(<span class="hljs-number">2</span>);
		ListNode&lt;Integer&gt; b = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		b.setData(<span class="hljs-number">3</span>);
		ListNode&lt;Integer&gt; c = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		c.setData(<span class="hljs-number">4</span>);
		ListNode&lt;Integer&gt; d = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		d.setData(<span class="hljs-number">100</span>);
		ListNode&lt;Integer&gt; e = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		e.setData(<span class="hljs-number">101</span>);
		ListNode&lt;Integer&gt; f = <span class="hljs-keyword">new</span> ListNode&lt;&gt;();
		f.setData(<span class="hljs-number">0</span>);

		<span class="hljs-comment">// 向链表的尾部添加三个节点</span>
		System.out.print(<span class="hljs-string">"the origin node: "</span>);
		list.insertAtListTail(headNode, a);
		list.insertAtListTail(headNode, b);
		list.insertAtListTail(headNode, c);
		list.traverseNode(headNode);
		System.out.println(<span class="hljs-string">"the length of the list: "</span> + list.getLength(headNode));

		<span class="hljs-comment">// 向链表中添加两个头结点( 头结点被更新 )</span>
		System.out.print(<span class="hljs-string">"add two header node: "</span>);
		ListNode&lt;Integer&gt; newHeadNode = list.insertAtListHeader(headNode, d);
		<span class="hljs-comment">// 注意: 由于`头结点`已在`insertAtListHeader`中已更新所以要向`traverseNode`传入新的头结点</span>
		ListNode&lt;Integer&gt; newHeadNode2 = list.insertAtListHeader(newHeadNode, e);
		list.traverseNode(newHeadNode2);
		System.out.println(<span class="hljs-string">"the length of the list: "</span> + list.getLength(headNode));

		<span class="hljs-comment">// 在链表的指定位置上插入新的节点</span>
		System.out.print(<span class="hljs-string">"Insert the new node at position 3: "</span>);
		list.insertNodeByIndex(headNode, f, <span class="hljs-number">3</span>);
		list.traverseNode(newHeadNode2);
		System.out.println(<span class="hljs-string">"the length of the list: "</span> + list.getLength(headNode));

		<span class="hljs-comment">// 删除链表的尾节点</span>
		System.out.print(<span class="hljs-string">"delete the tail node:  "</span>);
		list.deleteLastNode(newHeadNode2);
		list.traverseNode(newHeadNode2);
		System.out.println(<span class="hljs-string">"the length of the list: "</span> + list.getLength(headNode));

		<span class="hljs-comment">// 注意: 由于`头结点`已在`deleteHeaderNode`中已更新所以要向`traverseNode`传入新的头结点对象</span>
		ListNode&lt;Integer&gt; newHeadNode3 = list.deleteHeaderNode(newHeadNode2);
		System.out.print(<span class="hljs-string">"delete the header node:  "</span>);
		list.traverseNode(newHeadNode3);
		System.out.println(<span class="hljs-string">"the length of the list: "</span> + list.getLength(headNode));

		<span class="hljs-comment">// 删除链表中指定位置的节点</span>
		ListNode&lt;Integer&gt; newHeadNode4 = list.deleteNodeByIndex(newHeadNode3, <span class="hljs-number">4</span>);
		System.out.print(<span class="hljs-string">"delete the fourth node: "</span>);
		list.traverseNode(newHeadNode4);
		System.out.println(<span class="hljs-string">"the length of the list: "</span> + list.getLength(headNode));

	&#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs java">the origin node: 
### [headNode]-address : pers.huangyuhui.linkedlist.ListNode@16f65612

1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; headNode(1)
the length of the list: 4
add two header node: 
### [headNode]-address : pers.huangyuhui.linkedlist.ListNode@311d617d

101 -&gt; 100 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; headNode(101)
the length of the list: 6
Insert the new node at position 3: 
### [headNode]-address : pers.huangyuhui.linkedlist.ListNode@311d617d

101 -&gt; 100 -&gt; 1 -&gt; 2 -&gt; 0 -&gt; 3 -&gt; 4 -&gt; headNode(101)
the length of the list: 7
delete the tail node:  
### [headNode]-address : pers.huangyuhui.linkedlist.ListNode@311d617d

101 -&gt; 100 -&gt; 1 -&gt; 2 -&gt; 0 -&gt; 3 -&gt; headNode(101)
the length of the list: 6
delete the header node:  
### [headNode]-address : pers.huangyuhui.linkedlist.ListNode@7c53a9eb

100 -&gt; 1 -&gt; 2 -&gt; 0 -&gt; 3 -&gt; headNode(100)
the length of the list: 5
delete the fourth node: 
### [headNode]-address : pers.huangyuhui.linkedlist.ListNode@7c53a9eb

100 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; headNode(100)
the length of the list: 4</code></pre></div>


</li>
</ol>
<h3 id="基本数据类型作为参数传递"><a href="#基本数据类型作为参数传递" class="headerlink" title="基本数据类型作为参数传递"></a>基本数据类型作为参数传递</h3><ol>
<li><p><em>示例程序</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">test</span> </span>&#123;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
		<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>;
		System.out.println(<span class="hljs-string">"before change, i="</span> + i);
		change(i);
		System.out.println(<span class="hljs-string">"after change, i="</span> + i);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">change</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i)</span> </span>&#123;
		i = <span class="hljs-number">5</span>;
	&#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs java">before change, i=1
after change, i=1
```  

3. *结论*
   
*当`基本数据类型`作为参数传递时,传递时的是`实参的副本`,既传的是`值`,无论在函数中怎么操作这个副本,实参的值是不会被改变的.*



### 对象作为参数传递
1. *第一个示例程序*
```java
public class test &#123;

	public static void main(String[] args) &#123;

		StringBuffer sb = new StringBuffer("Hello");
		System.out.println("before change: " + sb);
		change(sb);
		System.out.println("after change: " + sb);
	&#125;

	private static void change(StringBuffer stringBuffer) &#123;
		stringBuffer.append(" world !");

	&#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs java">before change: Hello
after change: Hello world !</code></pre></div>
</li>
<li><p><em>探究结论</em></p>
</li>
</ol>
<p><em>从上述程序运行结果可知<code>sb</code>所指的对象的值被改变了!那么我们是否就可以认为Java中的对象作为参数传递时,传递的是该对象的引用呢 <code>?</code> 那我们再来看第二个示例程序.</em></p>
<ol start="4">
<li><em>第二个示例程序</em><div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">test</span> </span>&#123;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;

		StringBuffer sb = <span class="hljs-keyword">new</span> StringBuffer(<span class="hljs-string">"Hello"</span>);
		System.out.println(<span class="hljs-string">"before change: "</span> + sb);
		change(sb);
		System.out.println(<span class="hljs-string">"after change: "</span> + sb);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">change</span><span class="hljs-params">(StringBuffer stringBuffer)</span> </span>&#123;
		stringBuffer = <span class="hljs-keyword">new</span> StringBuffer(<span class="hljs-string">"Hi"</span>);
		stringBuffer.append(<span class="hljs-string">" world !"</span>);

	&#125;
&#125;</code></pre></div></li>
<li><em>程序运行结果</em></li>
</ol>
<p><em>如果上面的<code>推论</code>:(Java中对象作为参数传递时,实际传递的是该对象的引用)是正确的,那么在调用<code>change</code>函数后,原对象的值应该会被改变,既变为:<code>Hi World !</code>,但是,该程序的运行结果如下 !!!</em></p>
<div class="hljs"><pre><code class="hljs java">before change: Hello
after change: Hello</code></pre></div>
<p><em>可知原对象(<code>sb</code>)的值并没有被改变,这是为什么呢? 下面让我们来<code>分析</code>一下其中的原因吧嘿嘿 ~</em></p>
<ol start="6">
<li>结论分析</li>
</ol>
<p><em>当我们执行<code>StringBuffer sb = new StringBuffer(&quot;Hello&quot;)</code>时,我们便创建了一个指向新建对象<code>new StringBuffer(&quot;Hello&quot;)</code>的引用<code>sb</code>,如下所示.</em></p>
<div class="hljs"><pre><code class="hljs apache"><span class="hljs-attribute">sb</span> ——————&gt;<span class="hljs-meta"> [Hello]</span></code></pre></div>

<p><em>在<code>第二个示例程序</code>中,当我们调用<code>change</code>函数后,实际上,形参<code>stringBuffer</code>也指向了实参<code>sb</code>所指的对象! 如下所示.</em></p>
<div class="hljs"><pre><code class="hljs java">sb ——————&gt; [Hello] &lt;—————— stringBuffer</code></pre></div>
<p><em>那么当我们执行<code>stringBuffer.append(&quot;world!&quot;)</code>后,便通过对象的引用(<code>stringBuffer</code>)修改了对象的值,使之修改成了: <code>Hello world !</code>,如下所示:</em></p>
<div class="hljs"><pre><code class="hljs angelscript">sb ——————&gt; [Hello world !] &lt;—————— <span class="hljs-built_in">string</span>Buffer</code></pre></div>

<p><em>但是在<code>第二个示例程序</code>中的<code>change</code>函数中,我们又新建了一个对象:<code>new StringBuffer(&quot;Hi&quot;)</code>(该操作实际上是在内存中开辟了一块在原对象地址之外的<code>新区域</code>),这让形参<code>stringBuffer</code>实际指向了这个新建的对象,并将新对象的值设置为了<code>Hi world !</code>,如下所示:</em></p>
<div class="hljs"><pre><code class="hljs apache"><span class="hljs-attribute">sb</span> ——————&gt;<span class="hljs-meta"> [Hello]</span>
<span class="hljs-attribute">stringBuffer</span> ——————&gt;<span class="hljs-meta"> [Hi World !]</span></code></pre></div>
<ul>
<li><em>综上所述,可以得出结论: <code>在Java中,当对象作为参数传递时,实际上传递的是一份&quot;引用&quot;的拷贝 !</code></em></li>
</ul>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><em>在Java中, <code>=</code> 不能看成一个赋值语句,因为它并不是把一个对象赋给另一个对象的过程,它的执行过程实质上是将右边对象的<code>地址</code>传给了左边的引用,使得左边的引用指向了右边的对象.Java表面上看起来没有指针,但它的引用实质上就是一个<code>指针</code>,引用里面存放的并不是对象,而是存放该对象的地址,使得该引用指向了该对象.</em></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java/">Java</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/04/25/VOA-5-Habits-of-Very-Successful-People/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">VOA:5 Habits of Very Successful People</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/04/23/VOA-One-in-Five-Deaths-Linked-to-Unhealthy-Diet/">
                        <span class="hidden-mobile">VOA:One in Five Deaths Linked to Unhealthy Diet</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "详解Java对象的引用及赋值&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
